function loadCategories() {
    fetch('./DAO/category_DAO.php?action=getAllCategoriesJson')
        .then(response => response.json())
        .then(data => {
            const select = document.getElementById('categorySelect');
            data.forEach(category => {
                let option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                select.appendChild(option);
            });
            select.addEventListener('change', applyAdvancedFilters);
        });
}

function loadUserCart() {
    if (typeof globalUserId !== 'undefined' && globalUserId !== '0') {
        return fetch(`/DAO/user_cart_DAO.php?action=getUserCartByUserIdJson&userId=${globalUserId}`)
            .then(response => response.json())
            .then(data => {
                const cartItems = new Set();
                data.forEach(item => cartItems.add(item.product_id));
                updateCartIndicator(cartItems.size);
                return cartItems;
            })
            .catch(error => {
                console.error('Ошибка при загрузке корзины:', error);
                updateCartIndicator(0);
                return new Set();
            });
    } else {
        updateCartIndicator(0);
        return Promise.resolve(new Set()); 
    }
}

function updateCartIndicator(count) {
    const cartIndicator = document.getElementById('cartIndicator');
    if (count > 0) {
        cartIndicator.textContent = count;
        cartIndicator.style.display = 'block';
    } else {
        cartIndicator.style.display = 'none';
    }
}

function loadProducts(filters = {}) {
    let url = './DAO/product_DAO.php?action=getAllProductsJson';
    if (filters.categoryId) {
        url += '&categoryId=' + filters.categoryId;
    }
    if (filters.searchText) {
        url += '&searchText=' + filters.searchText;
    }
    if (filters.priceMin) {
        url += '&priceMin=' + filters.priceMin;
    }
    if (filters.priceMax) {
        url += '&priceMax=' + filters.priceMax;
    }
    if (filters.color) {
        url += '&color=' + filters.color;
    }
    if (filters.manufacturer) {
        url += '&manufacturer=' + filters.manufacturer;
    }
    if (filters.brand) {
        url += '&brand=' + filters.brand;
    }
    if (filters.energyConsumption) {
        url += '&energyConsumption=' + filters.energyConsumption;
    }
    if (filters.warranty) {
        url += '&warranty=' + filters.warranty;
    }

    loadUserCart().then(cartItems => {
        fetch(url)
        .then(response => response.json())
        .then(data => {
            const productList = document.getElementById('productList');
            productList.innerHTML = '';
            data.forEach(product => {
                let productDiv = document.createElement('div');
                productDiv.className = 'product';
                productDiv.onclick = () => openProductModal(product.id);
                let isProductInCart = cartItems.has(product.id);
                let clickHandler = isProductInCart ? '' : `onclick="addToCart(${product.id}, 'icon-container-${product.id}')"`;
                let iconClass = isProductInCart ? 'fa-check' : 'fa-plus';
                productDiv.innerHTML = `
                    <img src="${product.image_url}" alt="${product.name}" style="width:100%;">
                    <h3>${product.name}</h3>
                    <p>${product.description}</p>
                    <div class="product-price-cart">
                        <p>Цена: ${product.price} ₽</p>
                        <div class="icon-container" id="icon-container-${product.id}" ${clickHandler}>
                            <i class="fa-solid ${iconClass}"></i>
                        </div>
                    </div>
                `;
                productList.appendChild(productDiv);
            });
        });
    });
}

function openProductModal(productId) {
    loadUserCart().then(cartItems => {
        fetch(`./DAO/product_DAO.php?action=getProductById&id=${productId}`)
            .then(response => response.json())
            .then(product => {
                const modalContent = document.getElementById('modalProductContent');
                const isProductInCart = cartItems.has(product.id);
                const buttonText = isProductInCart ? 'В корзине' : 'Добавить в корзину';
                const buttonClass = isProductInCart ? 'in-cart' : 'add-to-cart';
                const buttonClickHandler = isProductInCart ? 'openCart()' : `addToCart(${product.id}, 'modalCartButton')`;
                modalContent.innerHTML = `
                    <div class="modal-product-details">
                        <img src="${product.image_url}" alt="${product.name}">
                        <div class="modal-product-info">
                            <h3>${product.name}</h3>
                            <p>${product.description}</p>
                            <p><strong>Цена:</strong> ${product.price} ₽</p>
                            <p><strong>Количество:</strong> ${product.quantity}</p>
                            <p><strong>Производитель:</strong> ${product.manufacturer}</p>
                            <p><strong>Бренд:</strong> ${product.brand}</p>
                            <p><strong>Энергопотребление:</strong> ${product.energy_consumption}</p>
                            <p><strong>Цвет:</strong> ${product.color}</p>
                            <p><strong>Гарантия:</strong> ${product.warranty} мес.</p>
                            <button id="modalCartButton" class="${buttonClass}" onclick="${buttonClickHandler}">
                                <i class="fa-solid ${isProductInCart ? 'fa-check' : 'fa-plus'}"></i> ${buttonText}
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('productModal').style.display = 'block';
            })
            .catch(error => console.error('Ошибка при загрузке продукта:', error));
    });
}

function closeModal() {
    document.getElementById('productModal').style.display = 'none';
}

document.addEventListener('DOMContentLoaded', function () {
    const closeButton = document.querySelector('.close-button');
    if (closeButton) {
        closeButton.addEventListener('click', function() {
            closeModal();
        });
    }
});

document.addEventListener('DOMContentLoaded', function () {
    const sidebarHandle = document.getElementById('sidebarHandle');
    const sidebar = document.getElementById('advancedFilterSidebar');

    sidebarHandle.addEventListener('mouseenter', function () {
        sidebar.classList.add('active');
    });

    sidebar.addEventListener('mouseleave', function () {
        sidebar.classList.remove('active');
    });
});

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('categorySelect').addEventListener('change', applyAdvancedFilters);
    document.getElementById('advancedFilterCheckbox').addEventListener('change', toggleAdvancedFilter);
    document.getElementById('searchInput').addEventListener('input', applyAdvancedFilters); 
});

function filterByCategory() {
    document.getElementById('searchInput').value = '';
    applyAdvancedFilters(); 
}

let debounceTimer;
function searchProducts(filters = {}) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        const searchText = document.getElementById('searchInput').value.toLowerCase();
        const categoryId = document.getElementById('categorySelect').value;
        const isAdvancedFilterChecked = document.getElementById('advancedFilterCheckbox').checked;

        filters.searchText = searchText;
        filters.categoryId = categoryId;

        if (isAdvancedFilterChecked) {
            const priceMin = document.getElementById('priceMin').value;
            const priceMax = document.getElementById('priceMax').value;
            const color = document.getElementById('colorSelect').value;
            const manufacturer = document.getElementById('manufacturerSelect').value;
            const brand = document.getElementById('brandSelect').value;
            const energyConsumption = document.getElementById('energyConsumptionSelect').value;
            const warranty = document.getElementById('warrantySelect').value;

            if (priceMin) filters.priceMin = priceMin;
            if (priceMax) filters.priceMax = priceMax;
            if (color) filters.color = color;
            if (manufacturer) filters.manufacturer = manufacturer;
            if (brand) filters.brand = brand;
            if (energyConsumption) filters.energyConsumption = energyConsumption;
            if (warranty) filters.warranty = warranty;
        }

        loadUserCart().then(cartItems => {
            fetch(buildUrlWithFilters('./DAO/product_DAO.php?action=getAllProductsJson', filters))
                .then(response => response.json())
                .then(data => {
                    const filteredData = searchText ? data.filter(product => product.name.toLowerCase().includes(searchText)) : data;
                    const productList = document.getElementById('productList');
                    productList.innerHTML = '';
                    filteredData.forEach(product => {
                        let productDiv = document.createElement('div');
                        productDiv.className = 'product';
                        productDiv.onclick = () => openProductModal(product.id);
                        let isProductInCart = cartItems.has(product.id);
                        let clickHandler = isProductInCart ? '' : `onclick="addToCart(${product.id}, 'icon-container-${product.id}')"`;
                        let iconClass = isProductInCart ? 'fa-check' : 'fa-plus';
                        productDiv.innerHTML = `
                            <img src="${product.image_url}" alt="${product.name}" style="width:100%;">
                            <h3>${product.name}</h3>
                            <p>${product.description}</p>
                            <div class="product-price-cart">
                                <p>Цена: ${product.price} ₽</p>
                                <div class="icon-container" id="icon-container-${product.id}" ${clickHandler}>
                                    <i class="fa-solid ${iconClass}"></i>
                                </div>
                            </div>
                        `;
                        productList.appendChild(productDiv);
                    });
                });
        }).catch(error => console.error('Ошибка при загрузке продуктов:', error));
    }, 300);
}

document.getElementById('categorySelect').onchange = () => {
    document.getElementById('searchInput').value = ''; 
    searchProducts({ categoryId: document.getElementById('categorySelect').value });
};

function openProfile() {
    if (isLoggedIn) {
        window.location.href = 'profile.php'; 
    } else {
        window.location.href = 'login.php'; 
    }
}

function openCart() {
    if (isLoggedIn) {
        window.location.href = 'cart.php';
    } else {
        window.location.href = 'login.php'; 
    }
}

function addToCart(productId, iconContainerId) {
    if (isLoggedIn) {
        fetch('/DAO/user_cart_DAO.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=addUserCart&user_id=${globalUserId}&product_id=${productId}&quantity=1`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Товар успешно добавлен в корзину');
                window.location.reload(); 
            } else {
                console.error('Ошибка при добавлении в корзину:', data.message);
            }
        })
        .catch(error => {
            console.error('Ошибка при добавлении в корзину:', error);
        });
    } else {
        window.location.href = 'login.php';   
    }
}

function initializeSlider() {
    const sliderContainer = document.getElementById('slider');
    const images = [
        '/images/other/promo_1.png',
        '/images/other/promo_2.png',
    ];

    const sliderInner = document.createElement('div');
    sliderInner.classList.add('slider-inner');

    images.forEach(image => {
        const slide = document.createElement('div');
        slide.classList.add('slider-image');
        slide.style.backgroundImage = `url(${image})`;
        sliderInner.appendChild(slide);
    });

    const firstClone = document.createElement('div');
    firstClone.classList.add('slider-image');
    firstClone.style.backgroundImage = `url(${images[0]})`;
    firstClone.id = 'first-clone';
    sliderInner.appendChild(firstClone);

    sliderContainer.appendChild(sliderInner);

    let currentImageIndex = 0;
    let intervalId;
    const imageWidth = sliderContainer.clientWidth;

    function setSlide(index) {
        sliderInner.style.transition = 'transform 1s ease-in-out';
        sliderInner.style.transform = `translateX(-${index * 100}%)`;
        currentImageIndex = index;
    }

    function moveToNextImage() {
        if (currentImageIndex >= images.length) {
            currentImageIndex = 0;
            sliderInner.style.transition = 'none';
            sliderInner.style.transform = `translateX(0)`;
            setTimeout(() => {
                sliderInner.style.transition = 'transform 1s ease-in-out';
                updateCarousel();
            }, 20);
        } else {
            updateCarousel();
        }
    }

    function updateCarousel() {
        currentImageIndex++;
        sliderInner.style.transform = `translateX(-${100 * currentImageIndex}%)`;
    }

    function startSlider() {
        intervalId = setInterval(moveToNextImage, 8000);
    }

    const prevButton = document.getElementById('prevButton');
    const nextButton = document.getElementById('nextButton');

    prevButton.addEventListener('click', () => {
        if (currentImageIndex <= 0) {
            currentImageIndex = images.length;
            sliderInner.style.transition = 'none';
            sliderInner.style.transform = `translateX(-${100 * currentImageIndex}%)`;
            setTimeout(() => {
                sliderInner.style.transition = 'transform 1s ease-in-out';
                currentImageIndex--;
                sliderInner.style.transform = `translateX(-${100 * currentImageIndex}%)`;
            }, 20);
        } else {
            currentImageIndex--;
            sliderInner.style.transform = `translateX(-${100 * currentImageIndex}%)`;
        }
        clearInterval(intervalId);
        startSlider();
    });

    nextButton.addEventListener('click', () => {
        moveToNextImage();
        clearInterval(intervalId);
        startSlider();
    });

    sliderInner.style.transform = `translateX(-${100}%)`;
    startSlider();

    sliderInner.addEventListener('mouseenter', () => clearInterval(intervalId));
    sliderInner.addEventListener('mouseleave', () => intervalId = setInterval(moveToNextImage, 8000));
}

document.addEventListener('DOMContentLoaded', initializeSlider);

function toggleAdvancedFilter() {
    const sidebar = document.getElementById('advancedFilterSidebar');
    const sidebarHandle = document.getElementById('sidebarHandle');
    const isChecked = document.getElementById('advancedFilterCheckbox').checked;
    if (isChecked) {
        sidebar.classList.add('active');
        sidebarHandle.classList.add('active'); 
        loadAdvancedFilters();
        applyAdvancedFilters(); 
    } else {
        sidebar.classList.remove('active');
        sidebarHandle.classList.remove('active'); 
        clearAdvancedFilters();
        const categoryId = document.getElementById('categorySelect').value;
        loadProducts({categoryId}); 
    }
}

function loadAdvancedFilters() {
    fetch('./DAO/product_DAO.php?action=getPriceRange')
        .then(response => response.json())
        .then(priceRange => {
            const minPrice = Number(priceRange.minPrice) || 0;
            const maxPrice = Number(priceRange.maxPrice) || 100000;

            const sidebar = document.getElementById('advancedFilterSidebar');
            sidebar.innerHTML = `
                <h3>Расширенный фильтр</h3>
                <label for="priceRange">Цена:</label>
                <div id="priceRange"></div>
                <div class="price-inputs">
                    <input type="number" id="priceMin" value="${minPrice}" min="${minPrice}" max="${maxPrice}">
                    <input type="number" id="priceMax" value="${maxPrice}" min="${minPrice}" max="${maxPrice}">
                </div>
                <label for="colorSelect">Цвет:</label>
                <select id="colorSelect" onchange="applyAdvancedFilters()">
                    <option value="">Все цвета</option>
                </select>
                <label for="manufacturerSelect">Производитель:</label>
                <select id="manufacturerSelect" onchange="applyAdvancedFilters()">
                    <option value="">Все производители</option>
                </select>
                <label for="brandSelect">Бренд:</label>
                <select id="brandSelect" onchange="applyAdvancedFilters()">
                    <option value="">Все бренды</option>
                </select>
                <label for="energyConsumptionSelect">Энергопотребление:</label>
                <select id="energyConsumptionSelect" onchange="applyAdvancedFilters()">
                    <option value="">Все классы</option>
                </select>
                <label for="warrantySelect">Гарантия:</label>
                <select id="warrantySelect" onchange="applyAdvancedFilters()">
                    <option value="">Все</option>
                </select>
            `;

            $("#priceRange").slider({
                range: true,
                min: minPrice,
                max: maxPrice,
                values: [minPrice, maxPrice],
                slide: function(event, ui) {
                    $("#priceMin").val(ui.values[0]);
                    $("#priceMax").val(ui.values[1]);
                    applyAdvancedFilters();
                }
            });

            $("#priceMin").val($("#priceRange").slider("values", 0));
            $("#priceMax").val($("#priceRange").slider("values", 1));
            $("#priceMin, #priceMax").on('change', function() {
                let min = $("#priceMin").val();
                let max = $("#priceMax").val();
                $("#priceRange").slider("values", [min, max]);
                applyAdvancedFilters();
            });

            fetchFilters();
        })
        .catch(error => console.error('Ошибка при загрузке диапазона цен:', error));
}

function clearAdvancedFilters() {
    document.getElementById('priceMin').value = '';
    document.getElementById('priceMax').value = '';
    document.getElementById('colorSelect').value = '';
    document.getElementById('manufacturerSelect').value = '';
    document.getElementById('brandSelect').value = '';
    document.getElementById('energyConsumptionSelect').value = '';
    document.getElementById('warrantySelect').value = '';
}

function applyAdvancedFilters() {
    const categoryId = document.getElementById('categorySelect').value;
    const searchText = document.getElementById('searchInput').value.toLowerCase();
    const isAdvancedFilterChecked = document.getElementById('advancedFilterCheckbox').checked;

    const filters = { searchText, categoryId };
    if (isAdvancedFilterChecked) {
        const priceMin = document.getElementById('priceMin').value;
        const priceMax = document.getElementById('priceMax').value;
        const color = document.getElementById('colorSelect').value;
        const manufacturer = document.getElementById('manufacturerSelect').value;
        const brand = document.getElementById('brandSelect').value;
        const energyConsumption = document.getElementById('energyConsumptionSelect').value;
        const warranty = document.getElementById('warrantySelect').value;

        if (priceMin) filters.priceMin = priceMin;
        if (priceMax) filters.priceMax = priceMax;
        if (color) filters.color = color;
        if (manufacturer) filters.manufacturer = manufacturer;
        if (brand) filters.brand = brand;
        if (energyConsumption) filters.energyConsumption = energyConsumption;
        if (warranty) filters.warranty = warranty;
    }

    loadProducts(filters);
}

function fetchFilters() {
    fetch('./DAO/product_DAO.php?action=getFilterOptions')
        .then(response => response.json())
        .then(data => {
            populateSelect('colorSelect', data.colors);
            populateSelect('manufacturerSelect', data.manufacturers);
            populateSelect('brandSelect', data.brands);
            populateSelect('energyConsumptionSelect', data.energyConsumptions);
            populateSelect('warrantySelect', data.warranties);
        })
        .catch(error => console.error('Ошибка при загрузке фильтров:', error));
}

function populateSelect(selectId, options) {
    const select = document.getElementById(selectId);
    select.innerHTML = '<option value="">Все</option>';
    options.forEach(option => {
        let opt = document.createElement('option');
        opt.value = option;
        opt.textContent = option;
        select.appendChild(opt);
    });
}

function buildUrlWithFilters(baseUrl, filters) {
    let url = new URL(baseUrl, window.location.origin);
    Object.keys(filters).forEach(key => {
        if (filters[key]) {
            url.searchParams.append(key, filters[key]);
        }
    });
    return url;
}
